var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var user = require('../../../utils/user.js');
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
var app = getApp();

Page({
  data: {
    userInfo: {
      nickName: '点击登录',
      avatarUrl: '/static/images/my.png'
    },
    order: {
      unpaid: 0,
      unship: 0,
      unrecv: 0,
      uncomment: 0
    }, 
    dealType1Count:0,
    dealType2Count:0,
    hasLogin: false
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数

    qqmapsdk = new QQMapWX({
      key: 'CIOBZ-RJNLX-VQ24X-7ZKQ4-YRMXK-MZBQC' //这里自己的key秘钥进行填充
    });
  },
  onReady: function() {
    
  },
  onShow: function() {
    //获取用户的登录信息
    if (app.globalData.hasLogin) {
      let that = this;  
      let userInfo = wx.getStorageSync('userInfo');
      that.setData({
        userInfo: userInfo,
        hasLogin: true
      });

      util.request(api.UserIndex).then(function(res) {
        if (res.code === 200) {
          that.setData({
            dealType1Count: res.dataObject.dealType1Count,
            dealType2Count: res.dataObject.dealType2Count
          });
        }
      });
    }
  },
  onHide: function() {
    // 页面隐藏

  },
  onUnload: function() {
    // 页面关闭
  },
  goLogin() {
    if (!this.data.hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }
  },
  goOrder() {
    if (this.data.hasLogin) {
      try {
        wx.setStorageSync('tab', 0);
      } catch (e) {

      }
      wx.navigateTo({
        url: "/pages/ucenter/order/order"
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }
  },
  goOrderIndex(e) {
    if (this.data.hasLogin) {
      let tab = e.currentTarget.dataset.index
      let route = e.currentTarget.dataset.route
      try {
        wx.setStorageSync('tab', tab);
      } catch (e) {

      }
      wx.navigateTo({
        url: route,
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      })
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },  
  goMyProductInfo(e){ 
    if (this.data.hasLogin) {
      let dealType = e.currentTarget.dataset.dealType
      let route = e.currentTarget.dataset.route
      try {
        wx.setStorageSync('dealType', dealType);
      } catch (e) {

      }
      wx.navigateTo({
        url: route,
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      })
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  goLogin() {
    wx.navigateTo({
      url: "/pages/auth/login/login"
    });
  },
  goCoupon() {
    if (this.data.hasLogin) {
      wx.navigateTo({
        url: "/pages/ucenter/couponList/couponList"
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  goGroupon() {
    if (this.data.hasLogin) {
      wx.navigateTo({
        url: "/pages/groupon/myGroupon/myGroupon"
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },    
  goCollect() {
    if (this.data.hasLogin) {
      wx.navigateTo({
        url: "/pages/ucenter/collect/collect"
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  goFeedback(e) {
    if (this.data.hasLogin) {
      wx.navigateTo({
        url: "/pages/ucenter/feedback/feedback"
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  goFootprint() {
    if (this.data.hasLogin) {
      wx.navigateTo({
        url: "/pages/ucenter/footprint/footprint"
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  goAddress() {
    if (this.data.hasLogin) {
      wx.navigateTo({
        url: "/pages/ucenter/address/address"
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },  
  bindPhoneNumber: function(e) {
    console.log(e);
    if (e.detail.errMsg !== "getPhoneNumber:ok") {
      // 拒绝授权
      return;
    }
    if (!this.data.hasLogin) {
      wx.showToast({
        title: '绑定失败：请先登录',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    util.request(api.AuthBindPhone, {
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData
    }, 'POST').then(function(res) {
      if (res.code === 200) {
        wx.showToast({
          title: '绑定手机号码成功',
          icon: 'success',
          duration: 2000
        });
      }
    });   
  },  
  bindMyPhone: function(e) {
    if (this.data.hasLogin) {
      let _phone = this.data.userInfo.phone;
      if(_phone > 0){ 
        wx.showToast({
          title: '手机号已绑定',
          icon: 'none',
          duration: 2000
        });
      }else{
        wx.navigateTo({
          url: "/pages/auth/mobile/mobile"
        });
      }
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  getMyUserLocation: function(e) {
    wx.getSetting({ 
      success: (res) => {
        console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })  
              }
            }
          })
        } 
        // else if (res.authSetting['scope.userLocation'] === true) {  
        //   wx.showLoading({
        //     title: '授权申请中...',
        //   });
        //   //调用wx.getLocation的API
        //   this.getLocation();
        // }
        else {
          wx.showLoading({
            title: '授权申请中...',
          }); 
          //调用wx.getLocation的API
          this.getLocation();
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        //let province = res.result.ad_info.province
        //let city = res.result.ad_info.city
        vm.updateLocation(res);
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  updateLocation: function(req) {
    let that = this;
    console.log(JSON.stringify(req));
    var _userInfo = that.data.userInfo; 
    let _province = req.result.ad_info.province;
    let _city = req.result.ad_info.city;
    let _district = req.result.ad_info.district;
    let _street = req.result.address_component.street;
    let _address = req.result.address;
    
    util.request(api.UserUpdateLocation, {
      latitude:req.result.ad_info.location.lat,
      longitude:req.result.ad_info.location.lng,
      nation:req.result.ad_info.nation,
      province:_province,
      city:_city,
      district:_district,
      street:_street,
      address:_address,
    }, 'POST').then(function(res) { 
      if (res.code === 200) {
         util.showErrorToast('位置授权成功');
         _userInfo.province = _province;
         _userInfo.city = _city;
         _userInfo.district = _district;
         _userInfo.street = _street;
         _userInfo.address = _address
         that.setData({
           userInfo:_userInfo,
        });
        // 更新缓存用户位置信息
        wx.setStorageSync('userInfo', _userInfo);
      } 
      wx.hideLoading();
    });
  },

  goAfterSale: function() {
    wx.showToast({
      title: '目前不支持',
      icon: 'none',
      duration: 2000
    });
  },
  aboutUs: function() {
    wx.navigateTo({
      url: '/pages/about/about'
    });
  },
  goHelp: function () {
    wx.navigateTo({
      url: '/pages/help/help'
    });
  },  
  exitLogin: function() {
    wx.showModal({
      title: '',
      confirmColor: '#b4282d',
      content: '退出登录？',
      success: function(res) {
        if (!res.confirm) {
          return;
        }
        util.request(api.AuthLogout, {}, 'POST');
        app.globalData.hasLogin = false;
        wx.removeStorageSync('token');
        wx.removeStorageSync('userInfo');
        wx.reLaunch({
          url: '/pages/index/index'
        });
      }
    })
  }
})